<script setup>
import  { tool }  from "../../tool/index"
import { ref, inject, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useStore } from "vuex"
// 初始化数据
const store = inject('store')
const user = ref(store.state.user) 
const commit = useStore()
const newEmail = ref('')
const code = ref('') 
const codeTemp = ref('') 
const codeTime = ref(30)
// 监听 VueX 变化
watch(() => {
  user.value = store.state.user
})
// 验证码倒计时
function startCountdown() {
  const time = setInterval(() => {
    if (codeTime.value > 0) {
      codeTime.value--
    } else {
      codeTime.value = 30
      clearInterval(time)
    }
  }, 1000)
}
// 发送验证码
async function sendCode() {
  code.value = Math.floor(1000 + Math.random() * 9000)
  console.log(code.value)
  const emailContent = {
    to: newEmail.value,
    subject: `博客园邮箱修改-验证码`,
    body: `您的验证码为：${code.value}`,
  }
  try {
    const EmailMessage = await tool.axiosApi("sendEmail", emailContent, "post")
    if (EmailMessage.message) {
      ElMessage.success("验证码发送成功，请检查邮箱")
      startCountdown()
    }
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  }
}
// 校验验证码 更改用户邮箱
function changeEmail() {
  console.log(codeTemp.value)
  if (code.value == codeTemp.value) {
    const Email = {
      email: newEmail.value
    }
    commit.commit("changeUser", Email)
    ElMessage.success("邮箱修改成功")
  }
}
</script>

<template>
  <div class="from">
    <el-form inline="true">
      <el-form-item label="原邮箱：">
        {{ user.email }}
      </el-form-item>
      <el-form-item label="请输入新邮箱">
        <el-input v-model="newEmail" />
      </el-form-item>
      <el-form-item>
        <el-button @click="sendCode" :disabled="codeTime === 30 ? false : true">
          {{ codeTime === 30 ? "发送验证码" : `请在${codeTime}秒后重试` }}
        </el-button>
      </el-form-item>
      <el-form-item label="请确认验证码">
        <el-input v-model="codeTemp" />
      </el-form-item>
      <el-form-item>
        <el-button @click="changeEmail" type="primary">确认修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.from {
  margin: auto;
  width: 500px;
}
</style>
